package com.yc.spring.aop;



import com.yc.spring.bbs.biz.UserBiz;
import com.yc.spring.bbs.dao.UserDao;
import com.yc.spring.bbs.dao.UserDaoImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

//CGLIB  动态字节码 基于继承方式  不要求被代理类实现接口
public class CglibProxy {
    public static Object proxy(Object target){
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target.getClass());
        //方法拦截器(回调)
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o,//代理对象
                                    Method method,//方法
                                    Object[] objects,//参数
                                    MethodProxy methodProxy//代理方法
            ) throws Throwable {
                Object ret = methodProxy.invoke(target,objects);
                System.out.println("后置拦截 " + methodProxy);

                return ret;
            }
        });
        //创建代理对象
        return enhancer.create();
    }

    public static void main(String[] args) {
        UserDao userDao = new UserDaoImpl();
        UserDao userDaoProxy = (UserDao) proxy(userDao);

        UserBiz userBiz = new UserBiz();
        UserBiz userBizProxy = (UserBiz) proxy(userBiz);

        userDaoProxy.insert(null);
        userBiz.modify(null);
        userBiz.getUser();
    }

}
